class AuthorizeController < ApplicationController
  layout "project"

  def list 
  
  @p_id = params[:id].to_i

   if request.post?
      @emps = params[:employees]
      @mngs = params[:managers]
      @project= Project.find(@p_id)
      @project.tasks.clear

      if not @emps.nil?
      @emps.each do |e|
        task = Task.create(:project=>@project,:user=> User.find(e),:role=>'Employee')
        @project.tasks << task 
      end     
      end     

      if not @mngs.nil?
      @mngs.each do |m|
        task = Task.create(:project=>@project,:user=> User.find(m),:role=>'Manager')
        @project.tasks << task 
      end     
      end     

      null_tasks = Task.find_by_sql "SELECT * FROM tasks WHERE project_id is NULL"

      null_tasks.each do |ntask| 
        ntask.destroy
    end
   end


  if @p_id >0
   @users = session[:user].company.users.to_a
   @employees = User.find_by_sql "SELECT users.* from users left join tasks on users.id=tasks.user_id where tasks.role='Employee' and tasks.project_id=#{@p_id}"
   @managers = User.find_by_sql "SELECT users.* from users left join tasks on users.id=tasks.user_id where tasks.role='Manager' and tasks.project_id=#{@p_id}"
   @a_users = @users - @employees - @managers
  else
   @a_users = {}
   @employees ={}
   @managers ={}
  end
  end
end
